var app = getApp();
var api = require('../../api.js');
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [
      '../../images/detail-img1.jpg',
      '../../images/detail-img2.jpg',
    ],
    indicatorDots: true,
    autoplay1: true,
    interval1: 5000,
    duration1: 500,

    currentTab: 0,
    tabArr: {
      curHdIndex: 0,
      curBdIndex: 0
    },

    urls: [
      '../../images/mall-goods002.jpg',
      '../../images/mall-goods001.jpg',
    ],
    goods_id:0,
    goods:{},
    goods_num:1,//选择的商品数量
    select_option:-1,//选择的商品规格index
    comment:[],
    rec_goods:[],
    cart_num:0,
    HiddenShare: true,
    HiddenShare1: true,
  },

  HiddenShareContent: function () {
    this.setData({
      HiddenShare: true
    })
  },

  popup1: function () {
    this.setData({
      HiddenShare: false
    })
  },

  GeneratePosters: function () {
    this.setData({
      HiddenShare: true
    })

  },
  ClosePosters: function () {
    this.setData({
      HiddenShare1: true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
    var page = this;
    if (options) {
      
      var tmp_options = wx.getStorageSync("tmp_options");
      if (tmp_options) {
        wx.setStorageSync("tmp_options", Object.assign(tmp_options, options))
      } else {
        wx.setStorageSync("tmp_options", options)
      }
      if(options.goods_id){
        page.setData({
          goods_id: options.goods_id
        })
      }
      if (options.scene) {
        var scene = decodeURIComponent(options.scene);
        scene = app.str2Obj(scene);
        this.setData({
          goods_id: scene.goods_id
        })
      }

      
      
    }
    this.getDetailInfo();
    wx.getSystemInfo({
      success(res) {
        page.setData({
          sys_info: res,
          user_info:wx.getStorageSync('user_info')
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var page = this
    var user = wx.getStorageSync('user_info');

    return {
      title: page.data.goods.name,
      path: '/pages/goods-details/goods-details?goods_id=' + page.data.goods_id + '&pid=' + user.user_id,
      imageUrl: page.data.goods.product_thumb,
    }
  },


//点击选择规格
  select_date: function (e) {
    this.setData({
      state1: e.currentTarget.dataset.key,
      select_option: e.currentTarget.dataset.key
    });
  },


//点击切换菜单
  tabFun: function (e) {
    //获取触发事件组件的dataset属性  
    var _datasetId = e.target.dataset.id;
    console.log("----" + _datasetId + "----");
    var _obj = {};
    _obj.curHdIndex = _datasetId;
    _obj.curBdIndex = _datasetId;
    this.setData({
      tabArr: _obj
    });
  }, 

//评论图片
  showGallery(e) {
    const dataset = e.currentTarget.dataset
    const current = dataset.current
    const urls = this.data.urls

    $wuxGallery.show({
      current: current,
      urls: urls,
      [`delete`](current, urls) {
        urls.splice(current, 1)
        this.setData({
          urls: urls,
        })
        return !0
      },
      cancel: () => console.log('Close gallery')
    })
  },
  previewImage(e) {
    const dataset = e.currentTarget.dataset
    const current = dataset.current
    const urls = this.data.urls

    wx.previewImage({
      current: current,
      urls: urls,
    })
  },

//禁止弹窗下面的内容滑动
preventTouchMove() { },

//规格弹窗的显示与隐藏
  setModalStatus: function (e) {
    console.log("设置显示状态，1显示0不显示", e.currentTarget.dataset.status);
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export()
    })
    if (e.currentTarget.dataset.status == 1) {
      this.setData(
        {
          showModalStatus: true
        }
      );
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (e.currentTarget.dataset.status == 0) {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200)
  },


  //服务弹窗的显示与隐藏
  setModalStatus2: function (e) {
    console.log("设置显示状态，1显示0不显示", e.currentTarget.dataset.status);
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    //animation.translateY(300).step()
    this.setData({
      animationData2: animation.export()
    })
    if (e.currentTarget.dataset.status == 1) {
      this.setData(
        {
          showModalStatus2: true
        }
      );
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (e.currentTarget.dataset.status == 0) {
        this.setData(
          {
            showModalStatus2: false
          }
        );
      }
    }.bind(this), 200)
  },


  //商品详情
  getDetailInfo:function(){
    wx.showLoading({
      title: '加载中',
    })
    var page = this;
    app.request({
      url: api.shop.goods_detail,
      method: 'POST',
      data: {
        goods_id:page.data.goods_id
      },
      success: function (res) {
        if (res.errcode == 0) {
          var content = res.data.detail + '<span> </span>'
          WxParse.wxParse("content", "html", content, page, 5);
          page.setData({
            goods: res.data,
            cart_num:res.data.cart_num
          });
          page.getGoodsComment();

        } else if (res.errcode == 3005){
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.errmsg,
          })
          setTimeout(
            wx.navigateTo({
              url: '../mall/mall',
            }),1000
          )
          return false;
          
        }
        else{
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.errmsg,
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.errmsg,
          showCancel: false
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  //商品评论
  getGoodsComment: function () {
    var page = this;
    app.request({
      url: api.shop.goods_comment,
      method: 'POST',
      data: {
        goods_id: page.data.goods_id
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            comment: res.data,
          });
          page.getGoodsRec()
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.errmsg,
          showCancel: false
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  //商品推荐
  getGoodsRec: function () {
    var page = this;
    app.request({
      url: api.shop.goods_rec,
      method: 'POST',
      data: {
        goods_id: page.data.goods_id
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            rec_goods: res.data,
          });
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.errmsg,
          showCancel: false
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },

  //立即购买
  payOrder:function(){
    var page = this;
    if (page.data.select_option == -1 && page.data.goods.goodsoption.length > 0) {
      if (page.data.showModalStatus == true) {
        wx.showToast({
          title: '请选择规格',
          icon: 'none'
        })
        return false;
      }
      page.setData({
        showModalStatus: true,
      })
      return false;
    } else {
      if (page.data.goods.goodsoption.length <= 0){
        wx.navigateTo({
          url: '../pay-order/pay-order?goods_id=' + page.data.goods.id + '&num=' + page.data.goods_num,
        })
      }else{
        wx.navigateTo({
          url: '../pay-order/pay-order?option_id=' + page.data.goods.goodsoption[page.data.select_option].id + '&num=' + page.data.goods_num,
        })
      }
      
    }
  },

  //加入购物车
  addCart:function(){
    var page = this;
    if(page.data.select_option==-1 && page.data.goods.goodsoption.length>0){
      if (page.data.showModalStatus==true){
        wx.showToast({
          title: '请选择规格',
          icon:'none'
        })
        return false;
      }
      page.setData({
        showModalStatus:true,
      })

      return false;
    }else{
      wx.showLoading({
        title: '提交中',
      })
      app.request({
        url: api.shop.addcart,
        method: 'POST',
        data: {
          goods_id: page.data.goods_id,
          optionid: page.data.select_option == -1 ? false : page.data.goods.goodsoption[page.data.select_option].id,
          total: page.data.goods_num
        },
        success: function (res) {
          if (res.errcode == 0) {
            page.setData({
              showModalStatus:false,
              cart_num: parseInt(res.data)
            });
            wx.showToast({
              title: '加入成功',
            })
          }
        },
        fail: function (res) {
          wx.showModal({
            title: '警告',
            content: res.errmsg,
            showCancel: false
          })
        },
        complete: function () {
          wx.hideLoading();
        }
      });
    }
  },
  //修改数量
  delNum:function(){
    var page = this;
    if(page.data.goods_num == 1){
      wx.showToast({
        title: '数量最低为1',
        icon:'none'
      })
      return false;
    }else{
      page.setData({
        goods_num: page.data.goods_num-1
      })
    }
  },
  //增加数量
  addNum: function () {
    var page = this;
    page.setData({
      goods_num: page.data.goods_num + 1
    })
    
  },
  createHaiBao: function () {
    wx.showLoading({
      title: '创建中',
    })
    var page = this;
    var goods_id = page.data.goods_id;
    app.request({
      url: api.shop.share_qrcode,
      method: "post",
      data: {
        id: goods_id
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            haibao: res.data
          })
          page.createNewImg()
        } else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
        }
      },
      complete: function (res) {
        wx.hideLoading();
      }
    });
  },

  /**
   * 生成二维码
   */

  createNewImg: function () {
    wx.showLoading({
      title: '生成中...',
    })
    var that = this;
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    that.GeneratePosters()
    var context = wx.createCanvasContext('mycanvas');
    // const ctx = canvas.getContext('2d');
    context.setFillStyle("#fff");
    context.fillRect(0, 0, width, height);


    //昵称
    context.setFontSize(15);
    context.setFillStyle('#000');
    context.setTextAlign('left');
    context.fillText(wx.getStorageSync('user_info').nickName, 80 * per_width, 60 * per_height, 280 * per_width);
    context.stroke();

    //昵称
    context.setFontSize(13);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText('我发现一个精彩的宝贝，快来看!', 80 * per_width, 90 * per_height, 280 * per_width);
    context.stroke();

    var text = that.data.goods.name;
    //标题
    context.setFontSize(14);
    context.setFillStyle('#333');
    context.setTextAlign('left');


    var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < 335 * per_width) {
        temp += chr[a];
      } else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);
    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < 220 * per_width) {
          test += rowPart[a];
        } else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..." //这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      context.fillText(row[b], 20 * per_width, (560 + b * 24) * per_height, 335 * per_width);
    }

    //提示
    context.setFontSize(13);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText('长按识别图中的小程序码', 180 * per_width, 640 * per_height, 280 * per_width);
    context.stroke();
    //提示
    context.setFontSize(13);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText('查看宝贝详情', 180 * per_width, 680 * per_height, 280 * per_width);
    context.stroke();
    that.setLogo(context); //绘制头像 
    // context.draw();
    context.fill()
    context.closePath()


  },
  darwAvatarArc: function (ctx, src, x, y, w, h = w) {
    ctx.save();
    ctx.beginPath()
    ctx.arc(x + w / 2, y + h / 2, w / 2, 0, Math.PI * 2, false);
    ctx.clip()
    ctx.drawImage(src, x, y, w, h);
    ctx.restore()
    ctx.draw(true)
  },

  setLogo(ctx) {
    var that = this;
    //that.darwAvatarArc(context, src, 50, 90, 45, 45);
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    var avatarurl_width = 45 * per_width; //绘制的头像宽度
    var avatarurl_heigth = 45 * per_width; //绘制的头像高度
    var avatarurl_x = 20 * per_width; //绘制的头像在画布上的位置
    var avatarurl_y = 40 * per_height; //绘制的头像在画布上的位置
    wx.downloadFile({
      url: that.data.haibao.headimg,
      success: function (res) {
        ctx.save()
        ctx.beginPath() //开始绘制
        ctx.setFillStyle('#fff')
        //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
        ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
        //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因    
        ctx.clip()
        ctx.drawImage(res.tempFilePath, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth);
        ctx.closePath()
        //恢复之前保存的绘图上下文 恢复之前保存的绘图上下文即状态 还可以继续绘制
        ctx.restore()
        //可将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中                                         
        that.setBanner(ctx)
      },
      fail(err) {
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })

      }
    })
  },


  setBanner: function (ctx) {
    var that = this;
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    wx.downloadFile({
      url: that.data.goods.product_thumb,
      success: function (res) {
        ctx.drawImage(res.tempFilePath, 20 * per_width, 120 * per_height, 335 * per_width, 335 * per_width);
        ctx.save();
        ctx.restore();
        //绘制奖品名字
        that.setQrcode(ctx)
      },
      fail(err) {
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })
      }
    })
  },
  setQrcode(ctx) {
    var that = this;
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    var avatarurl_width = 90 * per_width; //绘制的头像宽度
    var avatarurl_heigth = 90 * per_width; //绘制的头像高度
    var avatarurl_x = 60 * per_width; //绘制的头像在画布上的位置
    var avatarurl_y = 600 * per_height; //绘制的头像在画布上的位置
    wx.downloadFile({
      url: that.data.haibao.qr_img,
      success: function (res) {
        ctx.save()
        ctx.beginPath()
        ctx.setFillStyle('#dcdcdc')
        ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
        ctx.clip()
        ctx.drawImage(res.tempFilePath, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth);
        ctx.closePath()
        ctx.restore()
        that.showImg(ctx);
      },
      fail(err) {
        console.log(err);
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })

      }
    })
  },
  showImg(ctx) {
    var that = this;
    that.setData({
      HiddenShare1: false
    })
    ctx.draw(false, function (e) {
      console.log('绘制成功');
      that.saveTempCavans();

    })
  },
  saveTempCavans: function (e) {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      fileType: 'jpg',
      quality: 1,
      success: function (res) {
        // 获得图片临时路径
        that.setData({
          imagePath: res.tempFilePath,
          canvasHidden: true,
          HiddenShare1: false
        })
        that.imageTempPath = res.tempFilePath;
        that.imgSrc = that.imageTempPath;
        setTimeout(function () {
          wx.hideLoading();
        }, 200)
      },
      fail: function (res) {
        setTimeout(function () {
          that.saveTempCavans();
        }, 1000)
      }
    })
  },

  //点击保存到相册
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
              that.setData({
                HiddenShare1: true
              })
            }
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    })
  },


})